#include "MyModel.h"

MyModel::MyModel(QObject *parent) :
    QAbstractTableModel(parent)
{
    /*
    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerHit()));
    timer->start();
    */
}

int MyModel::rowCount(const QModelIndex &/*parent*/) const
{
    return ROWS;
}

int MyModel::columnCount(const QModelIndex &/*parent */) const
{
    return COLS;
}

QVariant    MyModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole)
    {
        return m_gridData[index.row()][index.column()];
    }
    return QVariant();


    int row = index.row();
    int col = index.column();

    qDebug() << QString("row %1, col %2, rol %3").arg(row).arg(col).arg(role);

    switch ( role )
    {
    case Qt::DisplayRole :
        if (row == 0 && col == 0) return QTime::currentTime().toString();
        if (row == 0 && col == 1) return QString("<--left");
        if (row == 1 && col == 1) return QString("right-->");
        return QString("Fil%1, Col%2").arg(row + 1).arg(col + 1);
        break;
//    case Qt::FontRole :
//        if (row == 0 && col == 0)
//        {
//            QFont   boldFont;
//            boldFont.setBold(true);
//            return boldFont;
//        }
//        break;
    case Qt::BackgroundRole :
        if (row == 1 && col == 2)
        {
            QBrush redBackground(Qt::red);
            return redBackground;
        }
        break;
    case Qt::TextAlignmentRole :
        if (row == 1 && col == 1)
        {
            return Qt::AlignRight + Qt::AlignVCenter;
        }
        break;
    case Qt::CheckStateRole :
        if (row == 1 && col == 0)
        {
            return Qt::Checked;
        }
        break;
    }

    return QVariant();
}

QVariant    MyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if ( ( role == Qt::DisplayRole ) && ( orientation == Qt::Horizontal ))
    {
        switch (section)
        {
        case 0:
            return QString("primero");
        case 1:
            return QString("segundo");
        case 2:
            return QString("tercero");
        }
    }
    return QVariant();
}

bool        MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if ( role == Qt::EditRole )
    {
        m_gridData[index.row()][index.column()]  = value.toString();
        QString result;
        for (int row = 0; row < ROWS; row++)
            for (int col = 0; col < COLS; col++)
                result += m_gridData[row][col] + "";
        emit editCompleted( result );
    }
    return false;
}

Qt::ItemFlags   MyModel::flags(const QModelIndex &/*index*/) const
{
    return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}

void    MyModel::timerHit()
{
    QModelIndex topLeft = createIndex(0, 0);
    emit dataChanged(topLeft, topLeft);
}
